{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PAX 工具平台</title>
    <link rel="icon" href="{% static 'pax/images/logo.png' %}" sizes="32x32" type="image/png">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .custom-btn {
            background-color: #417690;
            border-color: #417690;
        }
        .custom-btn:hover {
            background-color: #34607a;
            border-color: #34607a;
        }
        .custom-header {
            background-color: #417690;
        }
        .item-row {
            margin-bottom: 10px;
        }
        .remove-item {
            padding: 0.375rem;
        }
        .quantity-input {
            min-width: 80px;
        }
        .item-row .col-md-2 {
            display: flex;
            align-items: center;
        }
        .select2-container--default .select2-selection--single {
            height: 38px;
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
        .select2-container--default .select2-search--dropdown .select2-search__field {
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
        }
        .select2-dropdown {
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
        }
        /* 隐藏模板行 */
        [data-template] {
            display: none !important;
        }
        /* 验证错误样式 */
        .is-invalid-select ~ .select2 .select2-selection {
            border-color: #dc3545 !important;
        }
        /* 邮件类型单选按钮样式 */
        .mail-type-radio .btn-check:checked + .btn {
            background-color: #417690;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header text-white custom-header">
                        <h3 class="text-center">邮件</h3>
                    </div>
                    <div class="card-body">
                        <div id="error-message" class="alert alert-danger d-none"></div>
                        <div id="success-message" class="alert alert-success d-none"></div>
                        
                        <form id="queryForm" novalidate>
                            {% csrf_token %}
                            <div class="mb-3">
                                <label for="server" class="form-label">服务器</label>
                                <input type="text" class="form-control" id="server" name="server" placeholder="请输入服务器" required>
                                <div class="invalid-feedback">请填写服务器</div>
                            </div>
                            
                            <!-- 新增邮件类型选择 -->
                            <div class="mb-3">
                                <label class="form-label">邮件类型</label>
                                <div class="mail-type-radio btn-group w-100" role="group">
                                    <input type="radio" class="btn-check" name="mailType" id="mailType1" value="sausage" autocomplete="off" checked>
                                    <label class="btn btn-outline-secondary" for="mailType1">香肠邮件</label>
                                    
                                    <input type="radio" class="btn-check" name="mailType" id="mailType2" value="gold" autocomplete="off">
                                    <label class="btn btn-outline-secondary" for="mailType2">打金邮件</label>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">选择物品</label>
                                <div id="items-container">
                                    <!-- 模板行（隐藏） -->
                                    <div class="item-row row g-2 align-items-center" data-template>
                                        <div class="col-md-7">
                                            <select class="form-select item-select" name="items[]" required>
                                                <option value="">-- 请选择物品 --</option>
                                            </select>
                                            <div class="invalid-feedback">请选择物品</div>
                                        </div>
                                        <div class="col-md-3">
                                            <input type="number" class="form-control quantity-input" name="quantities[]" placeholder="数量" min="1" value="1" required>
                                            <div class="invalid-feedback">请输入有效数量</div>
                                        </div>
                                        <div class="col-md-2">
                                            <button type="button" class="btn btn-danger remove-item">
                                                <i class="bi bi-trash"></i> 删除
                                            </button>
                                        </div>
                                    </div>
                                    <!-- 初始行 -->
                                    <div class="item-row row g-2 align-items-center">
                                        <div class="col-md-7">
                                            <select class="form-select item-select is-invalid" name="items[]" required>
                                                <option value="">-- 请先选择服务器 --</option>
                                            </select>
                                            <div class="invalid-feedback">请选择物品</div>
                                        </div>
                                        <div class="col-md-3">
                                            <input type="number" class="form-control quantity-input" name="quantities[]" placeholder="数量" min="1" value="1" required>
                                            <div class="invalid-feedback">请输入有效数量</div>
                                        </div>
                                        <div class="col-md-2">
                                            <button type="button" class="btn btn-danger remove-item" disabled>
                                                <i class="bi bi-trash"></i> 删除
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <button type="button" id="add-item" class="btn btn-secondary mt-2">
                                    <i class="bi bi-plus"></i> 添加物品
                                </button>
                            </div>
                            
                            <div class="mb-3">
                                <label for="uid" class="form-label">用户UID</label>
                                <input type="text" class="form-control" id="uid" name="uid" placeholder="请输入用户UID" required>
                                <div class="invalid-feedback">请填写用户UID</div>
                            </div>
                            <button type="submit" class="btn btn-primary w-100 custom-btn">发送</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript 库 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // 初始化Select2
            function initSelect2(element) {
                $(element).select2({
                    placeholder: $(element).attr('placeholder') || '-- 请选择物品 --',
                    allowClear: false,
                    width: '100%',
                    language: {
                        noResults: function() {
                            return "没有找到匹配的选项";
                        }
                    }
                }).on('change', function() {
                    $(this).removeClass('is-invalid');
                    $(this).next('.invalid-feedback').hide();
                });
            }

            // 初始化第一行的Select2
            initSelect2($('.item-select').first());

            // 当前邮件类型
            let currentMailType = 'sausage';
            
            // 监听邮件类型变化
            $('input[name="mailType"]').change(function() {
                const newMailType = $(this).val();
                if (newMailType !== currentMailType) {
                    currentMailType = newMailType;
                    
                    // 清空所有物品选择
                    $('.item-row:not([data-template])').not(':first').remove();
                    const firstRow = $('.item-row:not([data-template])').first();
                    
                    // 重置第一行的选择
                    const select = firstRow.find('.item-select');
                    select.val(null).trigger('change');
                    select.empty().append('<option value="">-- 请先选择服务器 --</option>');
                    
                    // 重置数量
                    firstRow.find('.quantity-input').val(1);
                    
                    // 如果服务器已选择，重新加载物品
                    const server = $('#server').val();
                    if (server) {
                        loadItemsForRow(select, server);
                    }
                }
            });

            // 监听服务器输入变化
            $('#server').on('change', async function() {
                const server = $(this).val();
                if (server) {
                    try {
                        // 显示加载状态
                        $('.item-select').prop('disabled', true);
                        {% comment %} $('.item-select').not('[data-template]').html('<option>加载中...</option>'); {% endcomment %}
                        
                        // 调用API获取物品列表
                        const token = localStorage.getItem('pax_token');
                        const mailType = $('input[name="mailType"]:checked').val();
                        const response = await fetch("{% url 'item_view' %}?server=" + encodeURIComponent(server) + "&token=" + token + "&mail_type=" + mailType);
                        const items = await response.json();
                        const result = items.data;
                        
                        // 更新所有选择框的选项（排除模板）
                        $('.item-select').not('[data-template]').each(function() {
                            const select = $(this);
                            select.empty().append('<option value=""></option>');
                            result.forEach(item => {
                                select.append(new Option(item.name, item.id));
                            });
                            select.prop('disabled', false);
                            
                            // 重新初始化Select2
                            if (select.hasClass('select2-hidden-accessible')) {
                                select.select2('destroy');
                            }
                            initSelect2(select);
                        });
                        
                    } catch (error) {
                        console.error('加载物品失败:', error);
                        $('.item-select').not('[data-template]').html('<option>加载失败，请重试</option>');
                        $('.item-row:not([data-template])').not(':first').remove();
                    }
                }
            });
            
            // 添加物品行
            $('#add-item').click(function() {
                const template = $('[data-template]').first();
                const newRow = template.clone().removeAttr('data-template');
                
                // 完全重置选择框 - 先移除任何Select2生成的DOM元素
                const select = newRow.find('.item-select');
                select.next('.select2-container').remove(); // 移除Select2生成的容器
                select.removeClass('select2-hidden-accessible is-invalid');
                select.removeAttr('data-select2-id');
                select.empty().append('<option value=""></option>');
                
                // 重置数量输入
                newRow.find('.quantity-input').val(1).removeClass('is-invalid');
                
                // 启用删除按钮
                newRow.find('.remove-item').prop('disabled', false);
                
                // 添加到容器
                $('#items-container').append(newRow);
                
                // 初始化Select2
                initSelect2(select);
                
                // 如果服务器已选择，加载物品列表
                const server = $('#server').val();
                if (server) {
                    loadItemsForRow(select, server);
                }
            });
            
            // 为行加载物品列表
            async function loadItemsForRow(selectElement, server) {
                try {
                    selectElement.prop('disabled', true).html('<option>加载中...</option>');
                    
                    const token = localStorage.getItem('pax_token');
                    const mailType = $('input[name="mailType"]:checked').val();
                    const response = await fetch("{% url 'item_view' %}?server=" + encodeURIComponent(server) + "&token=" + token + "&mail_type=" + mailType);
                    const items = await response.json();
                    const result = items.data;
                    
                    selectElement.empty().append('<option value=""></option>');
                    result.forEach(item => {
                        selectElement.append(new Option(item.name, item.id));
                    });
                    selectElement.prop('disabled', false);
                    
                    // 重新初始化Select2
                    if (selectElement.hasClass('select2-hidden-accessible')) {
                        selectElement.select2('destroy');
                    }
                    initSelect2(selectElement);
                    
                } catch (error) {
                    console.error('加载物品失败:', error);
                    selectElement.html('<option>加载失败，请重试</option>');
                }
            }
            
            // 移除物品行
            $(document).on('click', '.remove-item', function() {
                if($('.item-row:not([data-template])').length > 1) {
                    $(this).closest('.item-row').remove();
                }
            });
            
            // 自定义表单验证
            function validateForm() {
                let isValid = true;
                
                // 验证服务器
                if (!$('#server').val()) {
                    $('#server').addClass('is-invalid');
                    isValid = false;
                } else {
                    $('#server').removeClass('is-invalid');
                }
                
                // 验证UID
                if (!$('#uid').val()) {
                    $('#uid').addClass('is-invalid');
                    isValid = false;
                } else {
                    $('#uid').removeClass('is-invalid');
                }
                
                // 验证物品行
                $('.item-row:not([data-template])').each(function() {
                    const $select = $(this).find('.item-select');
                    const $quantity = $(this).find('.quantity-input');
                    
                    if (!$select.val()) {
                        $select.addClass('is-invalid');
                        isValid = false;
                    } else {
                        $select.removeClass('is-invalid');
                    }
                    
                    if (!$quantity.val() || parseInt($quantity.val()) < 1) {
                        $quantity.addClass('is-invalid');
                        isValid = false;
                    } else {
                        $quantity.removeClass('is-invalid');
                    }
                });
                
                return isValid;
            }
            
            // 表单提交处理
            $('#queryForm').submit(async function(e) {
                e.preventDefault();
                
                // 手动验证表单
                if (!validateForm()) {
                    return;
                }
                
                const server = $('#server').val();
                const uid = $('#uid').val();
                const mailType = $('input[name="mailType"]:checked').val();
                const token = localStorage.getItem('pax_token');
                
                const attachments = [];
                $('.item-row:not([data-template])').each(function() {
                    const itemId = $(this).find('.item-select').val();
                    const quantity = $(this).find('.quantity-input').val();
                    const mailType = $('input[name="mailType"]:checked').val();
                    if (mailType=='gold'){
                        attachments.push({
                            Num: parseInt(quantity) || 1,
                            ItemId: itemId,
                            wear: 0,
                            entry1: 0,
                            entry2: 0,
                            entry3: 0,
                            entry4: 0,
                            mail_item_type: 1
                        });
                    }else{
                        attachments.push({
                            "Num": parseInt(quantity) || 1,
                            "ItemId": itemId,
                            "wear": 0,
                            "uuid": "0",
                            "mail_item_type": 0
                          });
                    }
                    
                });
                
                try {
                    const response = await fetch('{% url "send_email" %}', {
                        method: 'POST',
                        headers: { 
                            'Content-Type': 'application/json',
                            'X-CSRFToken': '{{ csrf_token }}'
                        },
                        body: JSON.stringify({
                            server_name: server,
                            uids: uid,
                            attachments: attachments,
                            token: token,
                            mail_type: mailType // 发送邮件类型到后端
                        })
                    });
                    
                    const data = await response.json();
                    if (data.success) {
                        $('#success-message').text('发送成功').removeClass('d-none');
                        setTimeout(() => $('#success-message').addClass('d-none'), 3000);
                    } else {
                        $('#error-message').text(data.error || '发送失败').removeClass('d-none');
                    }
                } catch (error) {
                    console.error('发送失败:', error);
                    $('#error-message').text('请求失败，请检查网络').removeClass('d-none');
                }
            });
            
            // 输入时移除错误状态
            $('input, select').on('input change', function() {
                $(this).removeClass('is-invalid');
            });
        });

        document.addEventListener('DOMContentLoaded', function() {
            const token = localStorage.getItem('pax_token');
            if (!token) {
                window.location.href = "{% url 'login' %}";
            }
        });
    </script>
</body>
</html>